import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';

import { Observable }     from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';


import { ApiService } from './api.service';

import { Staff } from '../domain/staff';


@Injectable()

export class StaffService {
  private api_url : string ;
  private headers : Headers ;

  constructor(private http: Http, private apiService: ApiService) {
    this.api_url = apiService.getUrl() + '/staffs';
    this.headers = apiService.getHeaders();
  }

  // 查询所有职员
  getHeroes(): Promise<Staff[]> {
    const url = `${this.api_url}`;
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as Staff[])
      .catch(this.handleError);
  }

  // 按id查询职员
  getStaffById(id: number): Promise<Staff> {
    const url = `${this.api_url}/${id}`;
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as Staff)
      .catch(this.handleError);
  }

  // 按账号 account 查询职员
  getStaffByAccount(account: string): Promise<Staff[]>{
    const url = '${this.api_url}/?account=${account}';
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as Staff[])
      .catch(this.handleError);
  }

  // 按姓名 name 查询职员
  getStaffByName(name: string): Promise<Staff[]>{
    const url = '${this.api_url}/?name=${name}';
    return this.http.get(url, { headers: this.headers })
      .toPromise()
      .then(res => res.json() as Staff[])
      .catch(this.handleError);
  }

  // 搜索职员
  searchStaff(term: string): Observable<Staff[]> {
    return this.http
      .get(`${this.api_url}?name_like=${term}`)
      .map(response => response.json() as Staff[]);
  }

  // 修改职员
  updateHero(staff: Staff): Promise<Staff> {
    const url = `${this.api_url}/${staff.id}`;
    return this.http
      .put(url, JSON.stringify(staff), { headers: this.headers })
      .toPromise()
      .then( res => res.json() as Staff)
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }
}


